import os
import pickle
import time
import subprocess
import win32com.client
import win32api
import win32con
import win32ui
import win32gui
from PIL import Image, ImageTk
from config_manager import config


def extract_icon_from_file(file_path):
    try:
        ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
        ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)

        large, small = win32gui.ExtractIconEx(file_path, 0)
        if large:
            hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
            hbmp = win32ui.CreateBitmap()
            hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_y)
            hdc = hdc.CreateCompatibleDC()
            hdc.SelectObject(hbmp)
            hdc.DrawIcon((0, 0), large[0])
            win32gui.DestroyIcon(large[0])

            bmpinfo = hbmp.GetInfo()
            bmpstr = hbmp.GetBitmapBits(True)
            img = Image.frombuffer(
                'RGBA',
                (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                bmpstr, 'raw', 'BGRA', 0, 1
            )

            if small:
                win32gui.DestroyIcon(small[0])

            return ImageTk.PhotoImage(img)
    except:
        pass

    return None


def get_shortcut_target(shortcut_path):
    shell = win32com.client.Dispatch("WScript.Shell")
    shortcut = shell.CreateShortCut(shortcut_path)
    return shortcut.Targetpath


def scan_shortcuts(directory):
    shortcuts = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.lnk'):
                shortcuts.append(os.path.join(root, file))
    return shortcuts


def open_shortcut(shortcut_path):
    try:
        subprocess.Popen(f'start "" "{shortcut_path}"', shell=True)
    except Exception as e:
        print(f"Error opening shortcut: {e}")


def load_cache():
    cache_file = os.path.join(config.cache_directory, 'shortcuts_cache.pkl')
    if os.path.exists(cache_file):
        try:
            with open(cache_file, 'rb') as f:
                cache_data = pickle.load(f)
                if time.time() - cache_data.get('timestamp', 0) < 3600:  # Cache valid for 1 hour
                    return cache_data.get('shortcuts', [])
        except:
            pass
    return None


def save_cache(shortcuts):
    os.makedirs(config.cache_directory, exist_ok=True)
    cache_file = os.path.join(config.cache_directory, 'shortcuts_cache.pkl')
    cache_data = {
        'shortcuts': shortcuts,
        'timestamp': time.time()
    }
    with open(cache_file, 'wb') as f:
        pickle.dump(cache_data, f)


def scan_all_shortcuts():
    shortcuts = []
    for directory in config.scan_directories:
        if os.path.exists(directory):
            shortcuts.extend(scan_shortcuts(directory))
    return shortcuts


def center_window(window):
    window.update_idletasks()
    width = window.winfo_width()
    height = window.winfo_height()
    x = (window.winfo_screenwidth() // 2) - (width // 2)
    y = (window.winfo_screenheight() // 2) - (height // 2)
    window.geometry(f'+{x}+{y}')


# PyQt版本的图标提取函数
def extract_icon_pyqt(file_path):
    """使用PyQt提取文件图标"""
    try:
        from PyQt5.QtWidgets import QFileIconProvider
        from PyQt5.QtCore import QFileInfo
        from PyQt5.QtGui import QIcon, QPixmap, QColor, QPainter
        from PyQt5.QtCore import Qt

        # 创建默认图标作为后备
        default_pixmap = QPixmap(32, 32)
        default_pixmap.fill(Qt.transparent)

        # 简单的文档图标
        painter = QPainter(default_pixmap)
        painter.setPen(QColor("#555555"))
        painter.setBrush(QColor("#DDDDDD"))
        painter.drawRect(8, 4, 16, 24)
        painter.drawLine(12, 12, 20, 12)
        painter.drawLine(12, 16, 20, 16)
        painter.drawLine(12, 20, 20, 20)
        painter.end()

        if not os.path.exists(file_path):
            print(f"文件不存在: {file_path}")
            return default_pixmap

        # 方法1: 使用QFileIconProvider (这是最安全的方法)
        try:
            provider = QFileIconProvider()
            fileInfo = QFileInfo(file_path)
            icon = provider.icon(fileInfo)
            if not icon.isNull():
                return icon.pixmap(32, 32)
        except Exception as e:
            print(f"使用QFileIconProvider提取图标失败: {e}")

        # 方法2: 直接使用QIcon
        try:
            icon = QIcon(file_path)
            if not icon.isNull():
                return icon.pixmap(32, 32)
        except Exception as e:
            print(f"使用QIcon提取图标失败: {e}")

        # 使用默认图标
        return default_pixmap
    except Exception as e:
        print(f"图标提取过程中出错: {e}")
        # 创建空白图标
        try:
            pixmap = QPixmap(32, 32)
            pixmap.fill(Qt.transparent)
            return pixmap
        except:
            return None
